package com.dagger.jobs;

import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.dagger.config.MsgConfig;
import com.dagger.constant.MessageConstants;
import com.dagger.utils.AbstractMsgUtil;

@Component
public class MessageJobs {
	@Autowired
	private RedisTemplate redisTemplate;
	
	@Autowired
	private MsgConfig msgConfig;
	
	private long cacheExpireSecond = 10;

	/**
	 * 刷新订阅的消息
	 */
	@Scheduled(fixedDelay = 1000 * 3)
	void resfreshMsgKeys() {
		AbstractMsgUtil.getAllMsgKey().forEach(msgKey -> {
			redisTemplate.opsForValue().set(MessageConstants.getCacheMsgKey(msgKey), msgKey, cacheExpireSecond, TimeUnit.SECONDS);
			long delayMillisecond = msgConfig.getDelayMillisecond(msgKey);
			if(delayMillisecond > 0) {
				//延时类消息，维护延时的队列过期时间
				redisTemplate.expire(MessageConstants.getDelayQueueKey(msgKey), cacheExpireSecond, TimeUnit.SECONDS);
				//为了标记该消息支持延时
				redisTemplate.opsForValue().set(MessageConstants.getDelayMillisecondKey(msgKey), delayMillisecond, cacheExpireSecond, TimeUnit.SECONDS);
			}
		});
	}
}
